$(function() {

    // 获取adList -- ok
    getAdList();
    // 页码切换 -- ok
    setChangePage(getAdList);
    /************************************************/

    // 搜索框 -- ok
    $('#adList-search').keydown(function (ev) {
        switch (ev.keyCode) {
            case 13 :
                oPageInfo.searchInfo = $('#adList-search').val();
                if( oPageInfo.searchInfo == oPageInfo.oldSearch ){
                    return false;
                }else{
                    oPageInfo.oldSearch = oPageInfo.searchInfo;
                    getAdList();
                }
                break;
            default :
                break;

        }
    });

    // 获取页面公告 --ok
    function getAdList() {
        let adList = new Promise((resolve, reject) => {
            $.ajax({
                url: '/manage/announcemen/search_announcemenn.do',
                type: 'post',
                data: {
                    name: oPageInfo.searchInfo,
                    pageNum: oPageInfo.pageNum,
                    pageSize: oPageInfo.pageSize,
                    time_sort : oPageInfo.time_sort
                },
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if (data.status == 0) {
                        resolve(data);
                    }else {
                        reject(data);
                    }
                }
            })
        });
        adList.then((data) => {
            oPageInfo.pageNum = data.data.pageNum;
            oPageInfo.pageSize = data.data.pageSize;
            oPageInfo.pages = data.data.pages;
            oPageInfo.pageTotal = data.data.total;
            oPageInfo.pageThisSize = data.data.size;
            oPageInfo.lastPage = data.data.lastPage;
            $('#table-tbody').html('');

            // 渲染至页面
            let adList = data.data.list;
            adList.forEach((item,idx)=>{
                let DOM = $('<tr data-id="'+ item.annno +'" data-top="'+ item.top +'">' +
                    '           <td style="padding-left: 15px;padding-bottom:0" width="45">' +
                    '               <input type="checkbox" data-top="' + item.top + '">' +
                    '           </td>' +
                    '           <td class="text-center fz-18" style="padding-bottom:0" width="45">' +
                    '               <i class="glyphicon glyphicon-envelope"></i>' +
                    '           </td>' +
                    '           <td>'+ item.creattime +'</td>' +
                    '           <td>' +
                    '               <a href="/noticeBoard.html?annno=' + item.annno + '">'+ item.annid +'</a>' +
                    '           </td>' +
                    '        </tr>');

                // 是否置顶
                if (item.top) {
                    DOM.addClass('danger Text-fwb');
                    DOM.find('td').eq(2).addClass('Text-red');
                    DOM.find('.glyphicon').removeClass('glyphicon-envelope').addClass('glyphicon-pushpin Text-red');
                    DOM.find('a').addClass('text-danger');

                    // 如果是置顶,添加至页面
                    $('#table-tbody').prepend( DOM );
                }else{
                    $('#table-tbody').append( DOM );
                }
            });

            // 设置 页码
            setPageFooter();
        }).catch( (data)=>{
            if( data.status == 10 ){
                spop_waring( data.msg, function () {}, outLogin )
            }
        });
    }

    // 事件排序 -- ok
    $('#AD_sortTime').on('click',function () {
        oPageInfo.time_sort = oPageInfo.time_sort == 0 ? oPageInfo.time_sort =1 : oPageInfo.time_sort = 0 ;
        $(this).find('i').toggleClass('active');
        getAdList();
    });

    // 全选按钮 -- ok
    $('#allChecked-OFF').on('click', function () {
        let OFF = $(this).is(':checked');
        let aOff_Checkbox = $('#table-tbody').find('input[type="checkbox"]');
        aOff_Checkbox.each( (idx,item)=>{
            $(item).prop('checked', OFF);
        } );

        // 置顶按钮CSS变化
        toTOPchange(aOff_Checkbox);
    });

    // 单个按钮 -- ok
    $('#table-tbody').on('change', 'input[type="checkbox"]', function () {
        let allChacked = $('#table-tbody').find('input[type="checkbox"]');
        let arr = [];

        // 转为数组进行
        allChacked.each( (idx,item)=>{
            arr.push( $(item).prop('checked') );
        });

        // 全true 输出true
        let thisOFF = arr.every(function (item, key, array) {
            return item == true;
        });

        // 全选按钮的变化
        if (thisOFF) {
            $('#allChecked-OFF').prop('checked', true);
        } else {
            $('#allChecked-OFF').prop('checked', false);
        }

        // 置顶按钮的切换
        toTOPchange(allChacked);

    });

    // 置顶公告 or 取消置顶 --ok
    $('#toTop-btn').on('click', function () {
        let aItemDOM = getChecked_true();

        if (aItemDOM) {
            let aID = [];

            aItemDOM.forEach( (item,idx)=>{
                aID.push( item.thisID );
            } );

            // 是否全部为置顶状态
            let OFF = aItemDOM.every(function (item, index, arr) {
                return Boolean( Number( item.thisTop ))
            });

            // 取消置顶
            if (OFF) {
                $.ajax({
                    url: '/manage/announcemen/announcemen_remove_top.do',
                    type: 'post',
                    data: {
                        annnoList: aID
                    },
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    success: function (data) {
                        if (data.status == 0) {
                            // 消息提示
                            spop_ok(data.msg, setTopCss(aItemDOM, false ,setCheckedNO ) );
                        }else if( data.status == 10 ){
                            spop_waring( data.msg, function () {}, outLogin )
                        } else {
                            spop_er(data.msg);
                        }
                    },
                    error: function (er) {
                        spop_er('未知错误');
                        console.log(er);
                    }
                });
            }
            // 置顶
            else {
                $.ajax({
                    url: '/manage/announcemen/announcemen_top.do',
                    type: 'post',
                    data: {
                        annnoList: aID
                    },
                    contentType: 'application/x-www-form-urlencoded',
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    success: function (data) {
                        console.log(data);
                        if (data.status == 0) {
                            // 消息提示
                            spop_ok(data.msg, setTopCss(aItemDOM, true, setCheckedNO) );
                        }else if( data.status == 10 ){
                            spop_waring( data.msg, function () {}, outLogin )
                        } else {
                            spop_er(data.msg);
                        }
                    },
                    error: function (er) {
                        spop_er('未知错误');
                    }
                });
            }
        } else {
            spop_er('未选中任何信息');
        }

    });

    // 删除公告 -- ok
    $('#del-btn').on('click', function () {
        let aItemID = getChecked_true();
        if (aItemID) {
            let aID = [];

            for (let i = 0; i < aItemID.length; i++) {
                aID.push(aItemID[i].thisID);
            }
            $.ajax({
                url: '/manage/announcemen/delete_announcemen.do',
                type: 'post',
                data: {
                    'annnoList[]': aID
                },
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if (data.status == 0) {
                        if ( oPageInfo.pageThisSize == 1 && oPageInfo.lastPage>1 ) {
                            oPageInfo.pageNum--;
                        }
                        spop_ok(data.msg, getAdList());
                    }else if( data.status == 10 ){
                        spop_waring( data.msg, function () {}, outLogin )
                    } else {
                        spop_waring(data.data);
                    }
                }
            });
        } else {
            spop_er('未选中任何信息');
        }
    });

    // 发布新公告 -- ok
    $('#newAD-btn').on('click', function () {
        window.location.href = './add-ad.html';
    });

    // 获取选中 公告 -ok
    function getChecked_true() {
        let aOff_Checkbox = $('#table-tbody').find('input[type="checkbox"]');

        let aItemID = [];

        aOff_Checkbox.each( (idx,item)=>{
            if( $(item).is( ":checked" ) ){
                let thisID = $(item).parents('tr').attr('data-id');// 获取ID
                let thisTop = $(item).parents('tr').attr('data-top');
                let thisDOM = $(item).parents('tr');
                aItemID.push({
                    thisID: thisID,
                    thisTop: thisTop,
                    thisDOM: thisDOM
                });
            }
        });

        if (Boolean(aItemID.length)) {
            return aItemID;
        } else {
            return false;
        }
    }

    // 置顶按钮切换  -ok
    function toTOPchange(activeChacked) {
        let aTop = [];

        activeChacked.each( (idx,item)=>{
            if( $(item).prop('checked') ){
                aTop.push($(item).parents('tr').attr('data-top'));
            }
        } );

        // 置顶按钮 的切换
        let topOFF = aTop.every(function (item) {
            return Boolean(Number(item));
        });
        console.log(topOFF);
        // 如果全是已置顶状态
        if (topOFF && aTop.length) {
            $('#toTop-btn').removeClass('btn-primary').addClass('btn-info').html('取消置顶');
        } else {
            $('#toTop-btn').removeClass('btn-info').addClass('btn-primary').html('置顶公告');
        }

    }

    // 按钮全不选  -- ok
    function setCheckedNO() {
        let aOff_Checkbox = $('#adTable').find('input[type="checkbox"]');

        aOff_Checkbox.each((idx,item)=>{
            // console.log(item);
            $(item).prop('checked', false);
        });
    }

    // 本地改变样式 -ok
    function setTopCss(DomList, OFF, callBack) {
        let off = null;
        // 列表
        DomList.forEach( (item,idx)=>{
            let tr = $(item.thisDOM);
            // 置顶
            if( OFF ){
                off = 1;

                tr.addClass('danger Text-fwb');
                tr.find('td').eq(2).addClass('Text-red');
                tr.find('.glyphicon').removeClass('glyphicon-envelope').addClass('glyphicon-pushpin Text-red');
                tr.find('a').addClass('text-danger');
            }else{// 取消
                off = 0;

                tr.removeClass('danger Text-fwb');
                tr.find('td').eq(2).removeClass('Text-red');
                tr.find('.glyphicon').addClass('glyphicon-envelope').removeClass('glyphicon-pushpin Text-red');
                tr.find('a').removeClass('text-danger');
            }
            tr.attr('data-top', off);
        } );
        // 按钮
        $('#toTop-btn').removeClass('btn-info').addClass('btn-primary').html('置顶公告');

        if( typeof callBack == 'function'){
            callBack();
        }
    }
});
